<template>
  <div>
    <!-- 组合模板 -->
    <el-dialog
      width="1100px"
      title="组合模板"
      destroy-on-close
      append-to-body
      center
      :visible.sync="show"
      :before-close="cancel"
    >
      <div style="margin: 10px 0">
        组合名称: <span style="font-weight: bold">{{ formData.combinationName }}</span>
      </div>
      <div>
        <el-select
          @change="setTemplateInfo"
          style="margin-right: 5px"
          size="mini"
          v-model="selectedTemplate"
          :placeholder="$t('请选择')"
        >
          <el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-button
          size="mini"
          v-hasPermi="['distribution:distrCombTemplate:insertUpdateDistrCombTemplate']"
          type="primary"
          @click="handleAddTemplate"
          v-show="!disabled"
        >
          新增模板
        </el-button>
        <el-button
          size="mini"
          type="success"
          @click="handleCopySelectedTemplate"
          v-if="selectedTemplate"
          v-hasPermi="['distribution:sku:skuTempCopy']"
        >
          复制当前模板
        </el-button>
      </div>
      <el-form
        v-if="type"
        ref="formRef"
        :disabled="disabled"
        :model="form"
        :rules="rules"
        size="mini"
        label-width="90px"
        style="margin-top: 10px"
      >
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="form.name" size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="平台sku" prop="combinationSku">
              <el-input v-model="form.combinationSku" size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="价格(JPY)" prop="price">
              <el-input
                size="mini"
                v-model="form.price"
                oninput="value=value.replace(/[^\d.]/g, '')"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label="$t('标题')" prop="title">
          <el-input v-model="form.title" size="mini" show-word-limit />
        </el-form-item>
        <el-row :gutter="20" style="margin-top: 15px">
          <el-col :span="10" style="padding-left: 0; padding-right: 0; border: 1px solid #eee">
            <!-- 五点描述 -->
            <div class="des-title">五点描述</div>
            <el-descriptions :column="1" border class="des-desc5">
              <el-descriptions-item label="描述1" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc1">
                  <el-input v-model="form.desc1" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="描述2" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc2">
                  <el-input v-model="form.desc2" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="描述3" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc3">
                  <el-input v-model="form.desc3" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="描述4" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc4">
                  <el-input v-model="form.desc4" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="描述5" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc5">
                  <el-input v-model="form.desc5" />
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="10">
            <!-- 详细描述 -->
            <div class="des-title" style="border: 1px solid #eee; border-bottom: none">详细描述</div>
            <div class="des-detail">
              <div class="des-detail_left">详情</div>
              <div class="des-detail_right">
                <el-form-item label-width="0" prop="descDetails">
                  <el-input
                    style="height: 100%"
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="form.descDetails"
                    :rows="12"
                  />
                </el-form-item>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div v-show="type != 'add'">
              <el-button
                type="danger"
                @click="deleteTemplate"
                size="small"
                v-hasPermi="['distribution:skuDistributor:deleteDistributorSkuTemplate']"
                v-show="selectedTemplate"
              >
                删除模板
              </el-button>
            </div>
            <div v-show="type == 'add'">
              <el-button
                size="mini"
                v-hasPermi="['distribution:distrCombTemplate:insertUpdateDistrCombTemplate']"
                type="success"
                style="margin-left: 10px"
                @click="addTemplate"
              >
                确认新增
              </el-button>
            </div>
          </el-col>
        </el-row>
        <div style="padding: 10px 0">模板图片</div>
        <el-row>
          <div class="template-img" :style="disabled ? 'pointer-events: none;' : ''">
            <ImgUploadManage
              type="4"
              :businessId="form.id"
              :uploadLimit="10"
              :limit="10"
              :fileList.sync="form.imgVoList"
            />
          </div>
        </el-row>
      </el-form>
      <div style="text-align: right; margin-top: 30px">
        <el-button
          v-hasPermi="['distribution:distrCombTemplate:insertUpdateDistrCombTemplate']"
          type="primary"
          @click="handleEdit"
          v-show="!disabled && type != 'add' && selectedTemplate"
        >
          修改模板
        </el-button>
        <el-button @click="cancel">{{ $t('关闭') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="500"
      :title="$t('复制模板')"
      destroy-on-close
      append-to-body
      :visible.sync="copySelectedTemplate.show"
      :before-close="() => (copySelectedTemplate.show = false)"
    >
      <el-form
        label-width="120px"
        @submit.native.prevent
        ref="copySelectedTemplateRef"
        :model="copySelectedTemplate.form"
        :rules="copySelectedTemplate.rules"
      >
        <el-form-item :label="$t('复制的模板名称')" prop="templateName">
          <el-input v-model="copySelectedTemplate.form.templateName" :placeholder="$t('请输入')" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleCopySelectedTemplateSubmit" type="primary">{{ $t('确认') }}</el-button>
        <el-button @click="copySelectedTemplate.show = false">{{ $t('关闭') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { insertUpdateDistrCombTemplate, remove, listNoPage } from '@/api/distribution/sku/assemblyList'
import { skuTempCopy } from '@/api/distribution/sku/skuInformation'
import draggable from 'vuedraggable'

export default {
  components: { draggable },

  props: {
    /**组合id */
    combinationId: {
      type: String,
    },
    /**
     * formData
     */
    formData: {
      type: Object,
      default: {},
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      originForm: '',
      copySelectedTemplate: {
        show: false,
        form: {
          templateName: '',
        },
        rules: {
          templateName: [{ required: true, message: this.$t('请输入'), trigger: 'blur' }],
        },
      },
      waitUploadList: [],
      uploadFlag: false,
      type: '',
      /**当前选择模板id */
      selectedTemplate: '',
      /**模板列表 */
      templateList: [],
      form: {
        id: '',
        combinationId: '',
        /**模板名称 */
        name: '',
        /**平台sku */
        combinationSku: '',
        /**价格(JPY) */
        price: '',
        /**标题 */
        title: '',
        /**描述1 */
        desc1: '',
        /**描述2 */
        desc2: '',
        /**描述3 */
        desc3: '',
        /**描述4 */
        desc4: '',
        /**描述5 */
        desc5: '',
        /**详情 */
        descDetails: '',
        /**模板图片 */
        imgVoList: [],
      },
      rules: {
        name: [{ validator: this.validLength, required: true, trigger: 'change' }],
        // combinationSku: [{ required: true, message: '请输入', trigger: 'blur' }],
        // price: [{ required: true, message: '请输入', trigger: 'blur' }],
        title: [{ validator: this.validLength, required: true, trigger: 'change' }],
        desc1: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc2: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc3: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc4: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc5: [{ validator: this.validLength, required: false, trigger: 'change' }],
        descDetails: [{ validator: this.validLength, required: false, trigger: 'change' }],
      },
    }
  },
  computed: {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.resetForm()
        this.getList()
      }
    },
  },
  methods: {
    handleCopySelectedTemplateSubmit() {
      this.$refs['copySelectedTemplateRef'].validate((valid) => {
        if (valid) {
          const data = {
            id: this.selectedTemplate,
            // type	类型 1-sku 2-组合
            type: 2,
            name: this.copySelectedTemplate.form.templateName,
          }
          skuTempCopy(data).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })
              this.getList()
              this.copySelectedTemplate.show = false
            }
          })
        }
      })
    },
    handleCopySelectedTemplate() {
      this.copySelectedTemplate.show = true
      this.copySelectedTemplate.form.templateName = ''
    },
    /**验证长度 */
    validLength(rule, value, callback) {
      const { field } = rule
      const strLength = value.length

      // name
      if (field == 'name') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 20
        if (strLength > 20) {
          return callback(new Error(`文字超长 ${strLength} / 20`))
        }
      }
      // descDetails
      if (field == 'descDetails') {
        //  长度最大为 3000
        if (strLength > 3000) {
          return callback(new Error(`文字超长 ${strLength} / 3000`))
        }
      }

      // title
      if (field == 'title') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 300
        if (strLength > 300) {
          return callback(new Error(`文字超长 ${strLength} / 300`))
        }
      }

      // 五点描述 长度最大为 500
      if (field == 'desc1' || field == 'desc2' || field == 'desc3' || field == 'desc4' || field == 'desc5') {
        // 五点描述 长度最大为 500
        if (strLength > 500) {
          return callback(new Error(`文字超长 ${strLength} / 500`))
        }
      }
      return callback()
    },

    deleteTemplate() {
      this.$confirm(this.$t('确认删除?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        remove(this.selectedTemplate).then((res) => {
          const { code, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })

            this.resetForm()
            this.getList()
          }
        })
      })
    },
    setTemplateInfo(id) {
      this.resetForm()
      const info = this.templateList.filter((item) => item.id == id || item.name == id)[0] || {}
      this.selectedTemplate = info.id
      Object.keys(this.form).forEach((key) => {
        const _data = JSON.parse(JSON.stringify(info))
        if (key == 'imgVoList') {
          this.form[key] = _data[key]?.map((i) => i.templateImgUrl)?.toString()
        } else {
          this.form[key] = _data[key] ? _data[key] : ''
        }
      })
      this.setOriginForm(this.form)
      // this.type = ''
      this.type = 'edit'
    },
    getList(templateName = null) {
      listNoPage({ combinationId: this.combinationId }).then((res) => {
        this.templateList = res.data
        /***************************设置相关信息******************************/
        if (templateName) {
          this.setTemplateInfo(templateName)
        } else {
          this.setTemplateInfo(this.templateList[0]?.id)
        }
        /***************************设置相关信息******************************/

        if (this.templateList.length == 0) {
          this.type = ''
        }
      })
    },
    handleAddTemplate() {
      this.type = 'add'
      this.selectedTemplate = ''
      const combinationTemplateId = JSON.parse(JSON.stringify(this.form)).id
      this.resetForm()
      this.form._combinationTemplateId = combinationTemplateId
      this.setOriginForm(this.form)
    },
    addTemplate() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = {
            ...this.form,
            combinationId: this.combinationId,
            imgVoList: this.form.imgVoList?.split(',')?.map((item, index) => {
              return {
                combinationTemplateId: this.form._combinationTemplateId,
                templateImgUrl: item,
                sort: index + 1,
              }
            }),
          }
          insertUpdateDistrCombTemplate(data).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              const templateName = JSON.parse(JSON.stringify(this.form.name))
              this.getList(templateName)
              this.type = ''
            }
          })
        }
      })
    },
    handleEdit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = {
            ...this.form,
            combinationId: this.combinationId,
            imgVoList: this.form.imgVoList?.split(',')?.map((item, index) => {
              return {
                combinationTemplateId: this.form.id,
                templateImgUrl: item,
                sort: index + 1,
              }
            }),
          }
          insertUpdateDistrCombTemplate(data).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              const templateName = JSON.parse(JSON.stringify(this.form.name))
              this.getList(templateName)
              this.type = ''
            }
          })
        }
      })
    },

    /**上传剩余文件 */
    uploadRestFile() {
      if (this.waitUploadList.length > 0) {
        this.uploadSingleFile()
      }
    },

    resetForm() {
      Object.keys(this.form).forEach((key) => (this.form[key] = ''))
      this.form.imgVoList = ''
      this.form.combinationId = this.combinationId
    },
    /**设置原始数据，为了检测关闭时是否改变 */
    setOriginForm(data) {
      this.originForm = JSON.stringify(data)
    },
    /**检测是否有改动 */
    checkChanges() {
      return JSON.stringify(this.form) == this.originForm
    },
    cancel() {
      if (!this.checkChanges()) {
        this.$confirm(this.$t('当前页面有改动没有保存，确认离开?'), this.$t('提示'), {
          type: 'warning',
        }).then(() => {
          this.$emit('update:show', false)
        })
      } else {
        this.$emit('update:show', false)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.el-form-item {
  // margin-bottom: 5px;
}

.my-label5 {
  text-align: center !important;
}

.des-title {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
.des-desc5 {
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}

.des-detail {
  display: flex;
  height: 265px;

  &_left {
    width: 40%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e1dddd;
  }

  &_right {
    padding: 10px;
    flex: 1;

    ::v-deep textarea {
      height: 100%;
    }
  }
}

.el-form-item {
  // margin-bottom: 5px;
}

.my-label5 {
  text-align: center !important;
}

.des-detail {
  display: flex;
  height: 265px;
  border: 1px solid #e1dddd;

  &_left {
    width: 40%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e1dddd;
  }

  &_right {
    padding: 10px;
    flex: 1;

    ::v-deep textarea {
      height: 100%;
    }
  }
}

.template-img {
  display: flex;
  overflow: auto;
  overflow-y: hidden;
  border: 1px solid #e1dddd;
  border-radius: 8px;
  padding: 5px;
}
</style>
